<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class DealerTypeStat extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
        protected $signature = 'command:DealerTypeStat';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $this->statOldData();
        return 0;
    }

    public function statOldData()
    {

        $start_month = strtotime('2018-01-01');
        $end_month = strtotime(date('Y-m-d'));

        for ($time = $start_month; $time < $end_month; $time += 86400) {
            $sql = 'SELECT count(1) AS total, mdtype, province_id, creator_id FROM users WHERE user_type=3 AND status=1 AND deleted_at IS NULL
                      AND created_at>="' . date('Y-m-d', $time) . '" AND created_at<"' . date('Y-m-d', $time + 86400) . '" GROUP BY mdtype, province_id';
            echo $sql; echo PHP_EOL;
            $data = DB::select($sql);
            if (empty($data)) {
                continue;
            }

            $insertData = [
                'create_date'   => date('Y-m-d', $time),
            ];
            foreach ($data as $item) {
                $province = DB::table('province_master')->where('id', $item->province_id)->first();
                if (!empty($province)) {
                    $insertData['province'] = $province->simplified_chiness_value;
                }
                $insertData['dist_id'] = $item->creator_id ?: 0;

                if ($item->mdtype == 0) {
                    $insertData['type_0_num'] = $item->total;
                    continue;
                }
                if ($item->mdtype == 1) {
                    $insertData['type_1_num'] = $item->total;
                    continue;
                }
                if ($item->mdtype == 2) {
                    $insertData['type_2_num'] = $item->total;
                    continue;
                }
                if ($item->mdtype == 3) {
                    $insertData['type_3_num'] = $item->total;
                    continue;
                }
                if ($item->mdtype == 4) {
                    $insertData['type_4_num'] = $item->total;
                    continue;
                }
                if ($item->mdtype == 5) {
                    $insertData['type_5_num'] = $item->total;
                    continue;
                }


            }

            DB::table('xpel_store_stat')->insert($insertData);
        }
    }
}
